<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<meta charset="utf-8">
	<title>恒铸智能柜管理平台</title>
	<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
			<meta name="viewport"
				content="width=device-width, initial-scale=1, maximum-scale=1">
				<meta name="apple-mobile-web-app-status-bar-style" content="black">
					<meta name="apple-mobile-web-app-capable" content="yes">
						<meta name="format-detection" content="telephone=no">
							<link rel="stylesheet"
								href="${pageContext.request.contextPath}/resources/layui/css/layui.css"
								media="all" />
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/js/cacheUserInfo.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/js/jquery-1.4.4.min.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/crypto/crypto.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/hmac/hmac.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/upload/lib/crypto1/sha1/sha1.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/upload/lib/base64.js"></script>
							<script type="text/javascript"
								src="${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/plupload.full.min.js"></script>
							<style>
.layui-input {
	width: 100%;
}

.file {
	position: relative;
}

.file input {
	position: absolute;
	left: 0px;
	height: 100%;
	width: 100%;
	opacity: 0;
}

.progress {
	margin-top: 2px;
	width: 200px;
	height: 14px;
	margin-bottom: 10px;
	overflow: hidden;
	background-color: #f5f5f5;
	border-radius: 4px;
	-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
	box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}

.progress-bar {
	background-color: rgb(92, 184, 92);
	background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.14902)
		25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.14902)
		50%, rgba(255, 255, 255, 0.14902) 75%, transparent 75%, transparent);
	background-size: 40px 40px;
	box-shadow: rgba(0, 0, 0, 0.14902) 0px -1px 0px 0px inset;
	box-sizing: border-box;
	color: rgb(255, 255, 255);
	display: block;
	float: left;
	font-size: 12px;
	height: 20px;
	line-height: 20px;
	text-align: center;
	transition-delay: 0s;
	transition-duration: 0.6s;
	transition-property: width;
	transition-timing-function: ease;
	width: 266.188px;
}
</style>
</head>
<body>
	<form class="layui-form">
		<div class="layui-form-item">
			<div class="layui-input-inline">
				<input type="text" id="url" name="url" style="display: none;">
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-input-inline">
				<input type="text" class="fileId" name="fileId"
					style="display: none;">
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">资源名称</label>
			<div class="layui-input-inline">
				<input type="text" class="layui-input name" name="name"
					placeholder="请输入资源名称" lay-verify="required">
			</div>
			<div class="layui-form-mid layui-word-aux">*</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">描述</label>
			<div class="layui-input-inline">
				<input type="text" class="layui-input des" name="des"
					placeholder="请输入描述">
			</div>
		</div>

		<div style="margin: 15px 0 15px 110px;">
			<div id="ossfile"></div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">文件上传</label>
			<div class="layui-input-inline">
				<div id="container">
					<a id="selectfiles" href="javascript:void(0);" class="layui-btn"
						id="test3"><i class="layui-icon"></i>上传文件</a>
				</div>
			</div>
			<div class="layui-form-mid layui-word-aux">*</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">选择类型</label>
			<div class="layui-input-inline">
				<select class="type" name="type" lay-verify="required">
					<c:if test="${sign ==0}">
						<option value="0" selected>图片</option>
						<option value="1">视频</option>
						<option value="2">音频</option>
					</c:if>
					<c:if test="${sign ==1}">
						<option value="0">图片</option>
						<option value="1" selected>视频</option>
						<option value="2">音频</option>
					</c:if>
					<c:if test="${sign ==2}">
						<option value="0">图片</option>
						<option value="1">视频</option>
						<option value="2" selected>音频</option>
					</c:if>
				</select>
			</div>
		</div>


		<div class="layui-form-item" style="margin: 30px 0 0 100px;">
			<a class="layui-btn" lay-submit lay-filter="editAd" type="sumbit">立即提交</a>
			<button type="reset" class="layui-btn layui-btn-primary">重置</button>
		</div>
	</form>
</body>
<script type="text/javascript">
	
	 var key="";
	 var flag=1;

	accessid= 'LTAIuTQ4eUb4Unt1';
	accesskey= 'Yo7NQiAb9MCObQTMqGA6UcOoGWWaIS';
	host = 'http://hengzhu-storage-1.oss-cn-hangzhou.aliyuncs.com';

	g_dirname = ''
	g_object_name = ''
	g_object_name_type = 'random_name'
	now = timestamp = Date.parse(new Date()) / 1000; 

	var policyText = {
	    "expiration": "2080-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
	    "conditions": [
	    ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
	    ]
	};

	var policyBase64 = Base64.encode(JSON.stringify(policyText))
	message = policyBase64
	var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
	var signature = Crypto.util.bytesToBase64(bytes);

	function random_string(len) {
	　　len = len || 32;
	　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
	　　var maxPos = chars.length;
	　　var pwd = '';
	　　for (i = 0; i < len; i++) {
	    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	    }
	    return pwd;
	}

	function get_suffix(filename) {
	    pos = filename.lastIndexOf('.')
	    suffix = ''
	    if (pos != -1) {
	        suffix = filename.substring(pos)
	    }
	    return suffix;
	}

	function calculate_object_name(filename)
	{
	    if (g_object_name_type == 'local_name')
	    {
	        g_object_name += "${filename}"
	    }
	    else if (g_object_name_type == 'random_name')
	    {
	        suffix = get_suffix(filename)
	        g_object_name = g_dirname + random_string(10) + suffix
	    }
	    return ''
	}

	function get_uploaded_object_name(filename)
	{
	    if (g_object_name_type == 'local_name')
	    {
	        tmp_name = g_object_name
	        tmp_name = tmp_name.replace("${filename}", filename);
	        return tmp_name
	    }
	    else if(g_object_name_type == 'random_name')
	    {
	        return g_object_name
	    }
	}

	function set_upload_param(up, filename, ret)
	{
	    g_object_name = g_dirname;
	    if (filename != '') {
	        suffix = get_suffix(filename)
	        calculate_object_name(filename)
	    }
	    new_multipart_params = {
	        'key' : g_object_name,
	        'policy': policyBase64,
	        'OSSAccessKeyId': accessid, 
	        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
	        'signature': signature,
	    };

	    up.setOption({
	        'url': host,
	        'multipart_params': new_multipart_params
	    });

	    up.start();
	}

	var uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selectfiles', 
	    //multi_selection: false,
		container: document.getElementById('container'),
		flash_swf_url : '${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/Moxie.swf',
		silverlight_xap_url : '${pageContext.request.contextPath}/resources/upload/lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',

		init: {
			PostInit: function() {
				document.getElementById('ossfile').innerHTML = '';
			},

			FilesAdded: function(up, files) {
				plupload.each(files, function(file) {
					document.getElementById('ossfile').innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
					+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
					+'</div>';
				});
				set_upload_param(uploader, '', false);
				flag=2;
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0]
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200)
	            {
	            	key = get_uploaded_object_name(file.name);
	            	var arr = key.split("/");
	            	
	            	key = arr[arr.length-1];
	            	document.getElementById("url").value = key;
	            	$("#ossfile div b span").html(" (上传完成) ")
	            	flag=1;
	            }
	            else
	            {
	            	flag=3;
	            } 
			},

			Error: function(up, err) {
				flag=3;
			}
		}
	});

	uploader.init();
	 //添加操作
	 layui.use(['form','layer','laydate','table','laytpl','element','upload'],function(){
	    var form = layui.form,
	        layer = parent.layer === undefined ? layui.layer : top.layer,
	        $ = layui.jquery,
	        laydate = layui.laydate,
	        laytpl = layui.laytpl,
	        element = layui.element,
	        table = layui.table;
	   	    upload = layui.upload;

	    form.on('submit(editAd)',function(data){
	    	if(flag==1){
				$.ajax({
					type: 'POST',
					url: "/publishFile/editFile",
					data: {
						fileId:$(".fileId").val(),
						name:$(".name").val(),
						url:key,
						des:$(".des").val(),
						type:$(".type").val()
					},
					success: function(rest){
						if(rest.success){
							layer.msg("修改成功");
							//parent.window.location.reload();
							 var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
							 parent.layer.close(index);
							 parent.layui.table.reload('adListTable') 
						}else{
							layer.msg(rest.message);
						}
					},
					contentType:'application/x-www-form-urlencoded; charset=UTF-8'
				});

	    	}else if(flag==2){
	    		layer.msg("还未上传完成，请耐心等待");
	    	}else if(flag==3){
	    		layer.msg("上传失败");
	    	}
		 }) 
	 });
</script>

</html>